<template>
  <!-- 咨询表单 -->
  <el-dialog
    :visible.sync="dialogVisible"
    width="40%"
    @close="close"
    :title="title">

    <el-form
      ref="consultForm"
      :rules="consultRules"
      status-icon
      :model="consult"
      label-width="100px">
      <el-form-item label="咨询内容：">
        <el-input v-model="consult.consult" disabled type="textarea" :rows="5"></el-input>
      </el-form-item>

      <el-form-item label="讲师回复：" prop="reply">
        <el-input v-model="consult.reply" type="textarea" :rows="6"  maxlength="200" show-word-limit ></el-input>
      </el-form-item>

    </el-form>


    <div slot="footer" class="dialog-footer">
      <el-button @click="close">取消</el-button>
      <el-button type="primary" @click="update">确定</el-button>
    </div>

  </el-dialog>
</template>

<script>
  import { getConsultById, updateConsultById} from '@/api/consult'
  import { validNormal } from '@/utils/validate'

  export default {
    data() {

      //检验回复
      const validateReply = (rule, value, callback) => {
        if (value.length < 10 || value > 200 || !validNormal(value)){
          callback(new Error("请输入正确的回复内容，长度要求为10-200，且不能输入特殊字符"))
        }
        else callback()
      }

      return {
        title: '',
        dialogVisible: false,
        consult: {
          consultId: '',
          consult: '',
          reply: ''
        },
        //检验规则
        consultRules:{
          reply: [{trigger: 'blur',validator: validateReply}]
        }
      }
    },

    methods: {
      open(consultId) {
        this.dialogVisible = true
        this.consult.consultId = consultId
        this.title = '回复课程咨询'
        getConsultById(consultId).then(result => {
          this.consult.consult = result.data.item.consult
          this.consult.reply = result.data.item.reply
        })
      },

      close() {
        this.$refs.consultForm.resetFields();
        this.dialogVisible = false
        // 重置表单
        this.resetForm()
      },

      resetForm() {
        this.consult.consultId = ''
        this.consult.consult = ''
        this.consult.reply = ''
      },

      update(){
        this.$refs.consultForm.validate((valid) => {
          if (valid) {
            //检验通过
            updateConsultById(this.$qs.stringify(this.consult)).then(result => {
              this.$message({
                type: 'success',
                message: '回复成功！'
              })
              // 关闭组件
              this.close()
              // 调用父组件监听函数
              this.$emit('onSaveSuccess')
            })
          }
          else {
            return false
          }
        })
      }
    }
  }
</script>

<style scoped>

</style>
